package Time;

import java.util.PriorityQueue;

//用来创建任务类，定时器需要执行的任务
class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable task;
    private long time;//需要一个客观的时间来表示具体什么时候执行

    public MyTimerTask(Runnable task, long delay) {
        this.task = task;
        this.time = delay + System.currentTimeMillis();
    }
    public long getTime() {
        return time;
    }
    public void run() {
        task.run();
    }

    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }
}
public class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    public MyTimer() {
        Thread thread = new Thread(() -> {
            try {
                while (true){//不断地从任务队列中取出任务执行
                    synchronized (this){
                        //1、取出元素
                        MyTimerTask task = queue.peek();
                        //2、判断是否到执行时间
                        long curTime = System.currentTimeMillis();
                        while (task == null){
                            this.wait();
                            task = queue.peek();
                        }
                        if(curTime >= task.getTime()) {//执行任务
                            task.run();
                            queue.poll();
                        }else {//继续等待
                            this.wait(task.getTime() - curTime);
                        }
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        thread.start();
    }
    public void schedule(Runnable task,long delay) {
        synchronized (this){
            MyTimerTask timerTask = new MyTimerTask(task,delay);
            queue.add(timerTask);
            this.notify();
        }
    }
}
class MyTest{
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        },1000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        },2000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        },3000);
    }
}
